﻿namespace CatClient.Util
{
    using System;
    using System.Collections.Concurrent;
    using System.Reflection;
    using System.Threading;

    public class CatThreadLocal<T> where T: class
    {
        private readonly ConcurrentDictionary<int, T> _mValues;

        public CatThreadLocal()
        {
            this._mValues = new ConcurrentDictionary<int, T>();
        }

        public void Dispose()
        {
            this._mValues.TryRemove(Thread.CurrentThread.ManagedThreadId, out _);
        }

        public T this[int threadId]
        {
            get
            {
                this._mValues.TryGetValue(threadId, out T local);
                return local;
            }
        }

        public T Value
        {
            get
            {
                T result = default(T);
                this._mValues.TryGetValue(Thread.CurrentThread.ManagedThreadId, out result);
                return result;
            }
            set
            {
                this._mValues[Thread.CurrentThread.ManagedThreadId] = value;
            }
        }
    }
}

